package com.house.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.house.common.BaseContext;
import com.house.entity.User;
import com.house.mapper.UserMapper;
import com.house.service.UserService;
import com.house.util.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public int save(User user) {
        String password = Md5Util.md5(user.getPassword());
        user.setPassword(password);
        user.setParentId(BaseContext.getThreadUserId());
        user.setStatus(1);
        return userMapper.insert(user);
    }

    @Override
    public Page<User> selectPage(int page, int pageSize, String userName) {
        Page<User> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getParentId, BaseContext.getThreadUserId());
        queryWrapper.like(userName != null, User::getUserName, userName);
        queryWrapper.orderByDesc(User::getCreateTime);
        return userMapper.selectPage(pageInfo, queryWrapper);
    }

    @Override
    public User selectUserByUserName(String userName) {
        return userMapper.selectByUserName(userName);
    }

    @Override
    public User selectUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public int update(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, user.getId());
        return userMapper.update(user, queryWrapper);
    }

    @Override
    public int delete(Long id) {
        return userMapper.delete(id);
    }
}
